package com.itheima.service;


import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringSecurityUserService2 implements UserDetailsService {
    @Autowired
     private BCryptPasswordEncoder passwordEncoder;
    //模拟数据库中的用户数据
    public  Map<String,User> map = new HashMap<>();

    public void initUserData(){
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));//明文密码（没有加密）

        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initUserData();
        System.out.println("用户名为"+username);
        //根据用户名查询用户信息（在数据库中包含密码信息）
        User user = map.get(username);//（模拟查询根据数据库查询用户信息）
        if (user == null){
            return null;
        }else {
            //将用户信息返回给框架
            //框架对密码进行比对（页面中提交的密码和数据库中的密码进行比对）
            List<GrantedAuthority> list = new ArrayList<>();
            //为当前登录用户授权，后期改为从数据库中查询用户的权限
            list.add(new SimpleGrantedAuthority("permission_A"));
            list.add(new SimpleGrantedAuthority("permission_B"));
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

            org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
            return securityUser;
        }





    }
}
